/*
 * customer权限下产品编辑修改
 * @Author: ljb
 * @Date: 2018-03-27 17:53:27
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-10-26 15:31:00
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .ivu-form-item-content {
        img {
            width: 150px;
        }
    }
</style>
<style lang="less" rel="stylesheet/less" type="text/less">
    .v-store-Product-edit{
        .ivu-radio-group {
            margin: 0 0 0px 4.16666667%;
        }
        .btn {
            margin-top: 15px;
        }
    }
</style>
<template>
	<div class="v-store-Product-edit">
		<Form
			ref="formValidate"
			:model="formValidate"
			:rules="ruleValidate"
			:label-width="labelWidth(90, 120)"
			name="store_edit__form">
			<!-- 类别 -->
			<Form-item
				:label="$t('product.category')"
				prop="category_id">
				<Select
					v-model="formValidate.category_id"
					clearable
					@on-change="changeCategory"
					@on-clear="clearCategory">
					<OptionGroup
						v-for="(item,key) in groupCategories"
						:key="key"
						:label="item.custom_type_name">
						<Option
							v-for="(value,key) in item.categories"
							:value="value.id"
							:key="key">{{ value.name }}</Option>
					</OptionGroup>
				</Select>
			</Form-item>
			<!-- 标题 -->
			<Form-item
				:label="$t('product.title')"
				prop="title">
				<i-input
					v-model="formValidate.title"
					:placeholder="$t('product.title')"
					name="store_edit__title"
					type="text"/>
			</Form-item>
			<!-- 简称 -->
			<Form-item
				:label="$t('product.name')"
				prop="name">
				<i-input
					v-model="formValidate.name"
					:placeholder="$t('product.name')"
					name="store_edit__name"
					type="text"/>
			</Form-item>
			<!-- 编码 -->
			<Form-item
				:label="$t('product.code')"
				prop="spu_code">
				<i-input
					v-model="formValidate.spu_code"
					:placeholder="$t('product.code')"
					type="text"/>
			</Form-item>
			<!-- 品牌 -->
			<Form-item
				:label="$t('product.brand')"
				prop="brand_id">
				<Select
					v-model="formValidate.brand_id"
					name="store_edit__brand_id"
					clearable
					filterable
					@on-change="changeBrans"
					@on-clear="clearBrans">
					<Option
						v-for="( value , key ) in brands"
						:value="key + ''"
						:key="key">{{ value }}</Option>
				</Select>
			</Form-item>
			<!-- 系列 -->
			<Form-item
				v-show="has_assets"
				:label="$t('product.series')"
				:prop="has_assets ? 'series' : ''">
				<Select
					v-model="formValidate.series"
					clearable>
					<Option
						v-for="(item) in brandList"
						:value="String(item.id)"
						:key="item.id">{{ item.name }}</Option>
				</Select>
			</Form-item>

			<!-- 标签 -->
			<Form-item
				v-if="!has_assets"
				:label="$t('product.tag')"
				prop="product_tag_ids">
				<Select
					v-model="formValidate.product_tag_ids"
					multiple
					clearable
					name="store_edit__product_tag_ids"
					filterable>
					<Option
						v-for="( value , key ) in productTags"
						:value="key + ''"
						:key="key">{{ value }}</Option>
				</Select>
			</Form-item>
			<!-- 身体部位 -->
			<!-- <Form-item
				v-if="!has_assets"
				:label="$t('product.body_positions')"
				prop="body_position_ids">
				<Select
					v-model="formValidate.body_position_ids"
					:placeholder="$t('product.body_positions')"
					clearable
					multiple>
					<Option
						v-for="( item , key ) in positions"
						:value="item.id"
						:key="key">{{ item.name }}
					</Option>
				</Select>
			</Form-item> -->
			<!-- 性别 -->
			<Form-item
				v-show="!has_assets"
				:label="$t('product.gender')"
				prop="stock">
				<RadioGroup v-model="formValidate.sex">
					<Radio :label="0">{{ $t('product.general') }}</Radio>
					<Radio :label="1">{{ $t('product.male') }}</Radio>
					<Radio :label="2">{{ $t('product.female') }}</Radio>
				</RadioGroup>
			</Form-item>
			<!-- 产品价格 -->
			<Form-item
				:label="$t('product.sell_price')"
				prop="sell_price">
				<InputNumber
					:min="0"
					:max="100000000"
					v-model="formValidate.sell_price"
					:placeholder="$t('product.sell_price')"
					name="store_edit__sell_price"/>
			</Form-item>
			<!-- 划线价 -->
			<Form-item
				:label="$t('product.market_price')"
				prop="market_price">
				<InputNumber
					:min="0"
					:max="100000000"
					v-model="formValidate.market_price"
					:placeholder="$t('product.market_price')"
					name="store_edit__market_price"/>
			</Form-item>
			<!-- 优先级 -->
			<Form-item
				:label="$t('product.priority')"
				prop="priority">
				<InputNumber
					:min="0"
					:max="100000"
					v-model="formValidate.priority"
					name="store_edit__priority"/>
			</Form-item>
			<!-- 模型文件 -->
			<Form-item
				v-show="has_assets"
				:label="$t('product.model_file')"
				prop="asset_id">
				<Select
					v-model="formValidate.asset_id"
					:placeholder="$t('product.no_model')"
					name="store_edit__asset_id"
					clearable>
					<Option
						v-for="model in models"
						:value="String(model.id)"
						:key="model.id">{{ model.code }}</Option>
				</Select>
			</Form-item>
			<!-- 商品链接类型 -->
			<Form-item
				v-if="Number(has_youzan) === 0"
				:label="$t('product.tb_link_type')"
				name="store_edit__product_url_type_id"
				prop="product_url_type_id">
				<Select
					v-model="formValidate.product_url_type_id"
					clearable
					name="store_edit__product_url_type_id">
					<Option
						v-for="chain in outerChain"
						:value="chain.id + ''"
						:key="chain.id">{{ chain.name }}</Option>
				</Select>
			</Form-item>
			<!-- 商品链接 -->
			<Form-item
				v-if="Number(has_youzan) === 0 && formValidate.product_url_type_id"
				:label="$t('product.tb_product_link')"
				:rules="[
					{
						required: true,
						message: $t('validate.required', { field: (productUrlType + $t('product.tb_product_link')) }),
						trigger: 'blur,change',
					},
					{
						type: 'url',
						message: $t('validate.url', { field: (productUrlType + $t('product.tb_product_link')) }),
						trigger: 'blur,change',
					},
				]"
				prop="product_url">
				<i-input
					v-model="formValidate.product_url"
					:placeholder="$t('product.please_enter_tb_link')"
					name="store_edit__product_url"
					type="text"/>
			</Form-item>
			<!-- 缩略图 -->
			<Form-item
				:label="$t('product.thumb')"
				prop="thumb">
				<Uploader
					ref="thumb"
					:default.sync="thumb_src"
					@on-remove="(file)=>{handleRemove('thumb',file)}"
					@on-change="(file)=>{handleChange('thumb',file)}">
					{{ $t('product.img_tip') }}
				</Uploader>
			</Form-item>
			<!-- 颜色缩略图 -->
			<Form-item
				v-show="has_assets"
				:label="$t('product.color_thumb')"
				prop="color_thumb">
				<Uploader
					ref="color_thumb"
					:default.sync="color_thumb_src"
					@on-remove="(file)=>{handleRemove('color_thumb',file)}"
					@on-change="(file)=>{handleChange('color_thumb',file)}">
					{{ $t('product.img_tip') }}
				</Uploader>
			</Form-item>

			<Form-item>
				<Button
					type="primary"
					name="store_edit__submit"
					@click="handleSubmit('formValidate')">
					{{ $t('common.update') }}
				</Button>
			</Form-item>

		</Form>
	</div>
</template>

<script>

import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { validateUpdateImage } from 'src/validate'; // validateCount 引入校验文件
import Uploader from 'src/views/component/Uploader';

export default {

	name: 'ProductEdit',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin],

	props: {
		productDetail: {
			type: Object,
			default() {
				return {};
			},
		},
		brands: {
			type: Object,
			default() {
				return {};
			},
		},
		groupBrands: {
			type: Array,
			default() {
				return [];
			},
		},
		outerChain: {
			type: Array,
			default() {
				return [];
			},
		},
		categories: {
			type: Array,
			default() {
				return [];
			},
		},
		groupCategories: {
			type: Array,
			default() {
				return [];
			},
		},
		productTags: {
			type: Object,
			default() {
				return {};
			},
		},
		modelsGroup: {
			type: Array,
			default() {
				return [];
			},
		},
		showModal: {
			type: Boolean,
			default() {
				return false;
			},
		},
		taobaoItem: {
			type: Object,
			default() {
				return {};
			},
		},
		showTaobaoModal: {
			type: Boolean,
			default() {
				return false;
			},
		},
		loading: {
			type: Boolean,
			default() {
				return false;
			},
		},
		positions: {
			type: Array,
			default() {
				return [];
			},
		},
		cosmeticMaterials: {
			type: Array,
			default() {
				return [];
			},
		},
	},

	data() {
		return {
			formValidate: {
				category_id: '', // 类别

				title: '', // 标题

				name: '', // 简称

				spu_code: '', // 编码

				brand_id: '', // 品牌

				product_mod_id: 0,

				series: '', // 系列

				material: '', // 材质

				product_tag_ids: [], // 标签

				body_position_ids: [], // 身体部位

				sex: 0, // 性别

				asset_id: '', // 模型文件

				sell_price: 0, // 产品价格

				market_price: 0, // 划线价

				priority: 0, // 优先级

				product_url_type_id: '', // 商品链接类型

				product_url: '', // 商品链接

				thumb: null, // 缩略图

				color_thumb: null, // 颜色缩略图
			}, // 更新产品时的表单

			has_assets: true, // 分类是否有素材

			models: [], // 模型文件

			has_youzan: 0, // 是否为有赞商品

			ruleValidate: { // 表单验证规则
				product_url_type_id: [
					{
						message: this.$t('validate.required', { field: this.$t('product.tb_link_type') }),
						trigger: 'blur,change',
					},
				],
				product_url: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.tb_product_link') }),
						trigger: 'blur,change',
					},
					{
						type: 'url',
						message: this.$t('validate.url', { field: this.$t('product.tb_product_link') }),
						trigger: 'blur,change',
					},
				],
				category_id: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.category') }),
						trigger: 'blur,change',
					},
				],
				brand_id: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.brand') }),
						trigger: 'blur,change',
					},
				],
				series: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.series') }),
						trigger: 'blur,change',
					},
				],
				material: [
					{
						message: this.$t('validate.required', { field: this.$t('product.material') }),
						trigger: 'blur,change',
					},
				],
				product_tag_ids: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('product.tag') }),
						trigger: 'blur,change',
					},
				],
				title: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.title') }),
						trigger: 'blur,change',
					},
				],
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.name') }),
						trigger: 'blur,change',
					},
				],
				spu_code: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.code') }),
						trigger: 'blur,change',
					},
				],
				market_price: [
					{
						// required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.market_price') }),
						trigger: 'blur,change',
					},
				],
				sell_price: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.sell_price') }),
						trigger: 'blur,change',
					},
				],
				priority: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.priority') }),
						trigger: 'blur,change',
					},
				],
				thumb: [
					{ required: true, validator: validateUpdateImage, trigger: 'blur,change' },
				],

				color_thumb: [
					{ validator: validateUpdateImage, trigger: 'blur,change' },
				],

				body_position_ids: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('product.body_positions') }),
						trigger: 'blur,change',
					},
				],
			},

			// 上传的图片信息
			thumb_src: '',
			// 上传的颜色缩略图片信息
			color_thumb_src: '',

			brandList: [], // 系列信息
		};
	},
	computed: {
		// 产品类型的name值
		productUrlType() {
			const { product_url_type_id } = this.formValidate;
			const selected_type = this.outerChain.filter(chain => parseInt(chain.id, 10) === parseInt(product_url_type_id, 10))[0];

			return selected_type ? selected_type.name : '';
		},
	},
	created() {
		this.initFormData();
	},
	methods: {

		/**
		 * 选择图片
		 * @param {Object} file {选择的文件对象集合}
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleChange(field, { file }) {
			this.formValidate[field] = file;
			this.$refs.formValidate.validateField(field);
		},

		/**
		 * 删除图片
		 * @param {String} filed {icon}
		 * @return {undefined}
		 */
		handleRemove(field) {
			if (field === 'color_thumb') {
				this.formValidate[field] = ''; // 提交 '' 值
			} else {
				this.formValidate[field] = null; // 不会提交
			}
			this.$refs.formValidate.validateField(field);
		},

		/**
		 *  初始化表单数据
		 * 	@return {undefined}
		 */
		initFormData() {
			this.formValidate.title = this.productDetail.title;
			this.formValidate.name = this.productDetail.name;
			this.formValidate.spu_code = this.productDetail.spu_code;
			this.formValidate.brand_id = this.productDetail.brand_id !== 0 ? String(this.productDetail.brand_id) : '';
			this.formValidate.product_url_type_id = !this.productDetail.product_url_type_id ? '' : String(this.productDetail.product_url_type_id);
			this.formValidate.asset_id = this.productDetail.asset ? String(this.productDetail.asset.id) : '';
			this.formValidate.market_price = parseFloat(this.productDetail.market_price);
			this.formValidate.sell_price = parseFloat(this.productDetail.sell_price);
			this.formValidate.priority = parseInt(this.productDetail.priority, 10);

			this.formValidate.product_url = this.productDetail.product_url === null ? '' : this.productDetail.product_url; // 商品链接
			this.formValidate.product_tag_ids = this.productDetail.product_tags.map(tag => String(tag.id)); // 商品链接类型
			this.brandList = this.takeBrans(this.productDetail.brand_id); // 获取系列数据
			this.$nextTick(() => {
				this.formValidate.series = this.productDetail.brand_series_id !== 0 ? String(this.productDetail.brand_series_id) : ''; // 系列
			}); // 是获取系列数据之后执行延迟回调
			// 是否有素材
			this.formValidate.body_position_ids = Array.isArray(this.productDetail.body_positions) ?
				this.productDetail.body_positions.map(item => item.id) : [];
			this.formValidate.category_id = this.productDetail.category ? this.productDetail.category.id : '';
			this.models = this.takeModels(this.formValidate.category_id);
			this.formValidate.sex = this.productDetail.sex ? this.productDetail.sex : 0;

			this.has_assets = (this.productDetail.category && !!this.productDetail.category.has_asset) || (this.isYouzan(this.productDetail) && !this.productDetail.category);

			// 补充
			this.has_youzan = this.productDetail.youzan_item_id;

			this.thumb_src = this.productDetail.thumb_image.key;
			this.color_thumb_src = this.productDetail.color_thumb_image !== null ? this.productDetail.color_thumb_image.key : '';
		},

		/**
		 * 判断产品是否是有赞商品
		 * @param  {Object} product {产品对象}
		 * @return {Boolean} {true代表是有赞商品，false代表不是}
		 */
		isYouzan(product) {
			return Number(product.youzan_item_id) !== 0;
		},

		/**
		 * 改变类型与模型关联文件
		 * @param  {Number} category_id {改变select获取到value值}
		 * @return {undefined}
		 */
		changeCategory(category_id) {
			if (category_id === '') { // 清空
				this.has_assets = true;
				this.resetTagAndPositionOptions();
				return;
			}
			const has_assets = this.hasModelAssets(category_id);
			this.models = this.takeModels(category_id);
			if (has_assets) {
				this.resetTagAndPositionOptions();
			} else {
				this.formValidate.asset_id = null;
			}
			this.has_assets = has_assets;
		},

		/**
		 * 改变品牌与系列文件
		 * @param {String} brand_id {改变select获取到value值}
		 * @return {undefined}
		 */
		changeBrans(brand_id) {
			this.brandList = this.takeBrans(brand_id);
			this.formValidate.series = '';
		},

		/**
		 * 清空类型与模型关联文件
		 * @return {Array}
		 */
		clearBrans() {
			this.brandList = [];
		},

		/**
		 *  重置标签/身体部位选项
		 *  @return {Array}
		 */
		resetTagAndPositionOptions() {
			this.formValidate.product_tag_ids = [];
			this.formValidate.body_position_ids = [];
		},

		/**
		 *  获取模型
		 *  @param {number} category_id {类型选中的值value}
		 *  @return {array} models
		 */
		takeModels(category_id) {
			let models = [];
			this.modelsGroup.forEach((item) => {
				if (item.category_id === category_id) {
					models = item.assets;
				}
			});
			return models;
		},

		/**
		 *  获取系列信息
		 * @param {Number} id {选取value}
		 * @return {undefined}
		 */
		takeBrans(id) {
			let brans = [];
			this.groupBrands.forEach((item) => {
				if (item.id === Number(id)) {
					brans = item.brand_series;
				}
			});
			return brans;
		},

		/**
		 * 是否有模型素材
		 * @param {number} category_id {类型选中的值value}
		 * @return {boolean} has_assets
		 */
		hasModelAssets(category_id) {
			const [category] = this.categories.filter(item => item.id === category_id);
			return category && !!category.has_asset;
		},

		/**
		 *清空类型与模型关联文件
		 * @return {Array}
		 */
		clearCategory() {
			this.models = [];
		},

		/**
         * 更新商品信息
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleSubmit(name) {
			if (this.loading) return;
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.$emit('update', this.productDetail.id, this.formDataCreate());
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 手动拼接formdata数据
         * @return {Object}
         */
		formDataCreate() {
			const new_object = {
				_method: 'PUT',

				category_id: this.formValidate.category_id,

				brand_id: this.formValidate.brand_id,

				product_mod_id: 0,

				title: this.formValidate.title,

				name: this.formValidate.name,

				spu_code: this.formValidate.spu_code,

				market_price: this.formValidate.market_price,

				sell_price: this.formValidate.sell_price,

				thumb: this.formValidate.thumb,

				color_thumb: this.formValidate.color_thumb,

				model_xml: this.formValidate.model_xml,

				priority: this.formValidate.priority,

				product_url: this.formValidate.product_url,

				product_url_type_id: this.formValidate.product_url_type_id,

				asset_id: this.has_assets ? this.formValidate.asset_id : null,

				sex: !this.has_assets ? this.formValidate.sex : null,

				body_position_ids: !this.has_assets ? this.formValidate.body_position_ids : null,

				product_tag_ids: !this.has_assets ? this.formValidate.product_tag_ids : null,

				cosmetic_material_id: this.formValidate.material ? this.formValidate.material : null,

				brand_series_id: this.formValidate.series ? this.formValidate.series : null,
			};

			const form_data = new FormData();

			Object.keys(this.skipNulls(new_object))
				.forEach((key) => {
					switch (key) {
					case 'product_tag_ids':
						if (new_object[key].length > 0) {
							new_object[key].forEach((tag, index) => {
								form_data.append(`${key}[${index}]`, tag);
							});
						}

						break;
					case 'body_position_ids':
						if (new_object[key].length > 0) {
							new_object[key].forEach((value, index) => {
								form_data.append(`${key}[${index}]`, value);
							});
						}
						break;
					default:
						form_data.append(key, new_object[key]);

						break;
					}
				});

			return form_data;
		},

		/**
		 * 跳过对象中的 null 值元素
		 * @param {Object} source {手动拼接对象}
		 * @returns {Object} target
		 */
		skipNulls(source) {
			const target = {};
			Object.keys(source)
				.forEach((key) => {
					const is_null = typeof source[key] === 'object' && !source[key];
					if (!is_null) {
						Object.assign(target, { [key]: source[key] });
					}
				});
			return target;
		},

	},
};
</script>
